package com.base.cn.platform.os.controller.op.affiche;

import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.msg.WXTmpEnum;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.op.affiche.OpReceiveAffiche;
import com.base.cn.platform.os.entity.order.order.Order;
import com.base.cn.platform.os.service.course.classes.member.ClassesMemberService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.base.cn.platform.os.service.op.affiche.OpReceiveAfficheBiz;
import com.base.cn.platform.os.service.op.affiche.tmp.SendMessage;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 接收消息Controller
 *
 * @author zsw
 * @create 2018/6/1
 */
@RestController
@RequestMapping("/manage/op")
public class OpReceiveAfficheController extends BaseController {

    @Autowired
    private OpReceiveAfficheBiz receiveAfficheBiz;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private ClassesMemberService classesMemberService;
    @Autowired
    private SendMessage sendMessage;
    @Autowired
    private CustomCacheChannel customCacheChannel;
/*
    @RequestMapping("/test")
    public void test(){
        Order order = new Order();
        order.setOrderNo(DateUtils.format(new Date(),"yyyyMMddHHmmSSS"));
        order.setRealPrice(100D);
        BigDecimal userId = new BigDecimal(1);
        Map<BigDecimal,List> dataListMap = new HashMap<>();
        dataListMap.put(userId,Arrays.asList(order));
        sendMessage.sendMessage(WXTmpEnum.ORDER,Arrays.asList(userId),dataListMap);
    }*/

    /**
     * 系统自动发送消息
     * @param key 消息模板类型KEY
     */
    @RequestMapping("/sendMessage")
    public void sendMessage(@RequestParam("key") String key){
        Map<BigDecimal,Object> dataMap = (Map<BigDecimal,Object>)customCacheChannel.get(J2CacheRegion.ONE_HOURS_REGION.getKey(),key).getValue();
        if(dataMap !=null){
            List<BigDecimal> userIdList = (List<BigDecimal>)dataMap.get("userIdList");
            Map<BigDecimal,List> dataListMap = (Map<BigDecimal,List>)dataMap.get("dataListMap");
            WXTmpEnum tmpEnum = (WXTmpEnum)dataMap.get("key");
            sendMessage.sendMessage(tmpEnum,userIdList,dataListMap);
            customCacheChannel.evict(J2CacheRegion.ONE_HOURS_REGION.getKey(),key);
        }
    }

    /**
     * 修改消息状态为已读
     * @param id 消息ID
     * @return Map<String,Object>
     */
    @RequestMapping("/updateReceiveAfficheById")
    public Map<String,Object> updateReceiveAfficheById(@RequestParam("id") BigDecimal id,@RequestParam("userId") BigDecimal userId){
        receiveAfficheBiz.updateReceiveAfficheById(id,userId);
        return ResultUtil.SUCCESS();
    }

    /**
     * 批量获取管理发送的消息数据添加到接收表中
     *
     * @param userId
     */
    @RequestMapping("/saveReceiveAffichBatch")
    public void saveReceiveAffichBatch(@RequestParam("userId") BigDecimal userId) {
        receiveAfficheBiz.addBatchReceiveAffiche(userId);
    }

    /**
     * 查询接收消息列表
     *
     * @param currentPage    分页
     * @param receiveAffiche 查询条件
     * @param subjectData    是否设置专业科目
     * @param courseData     是否设置课程
     * @param sysUserData    是否设置创建人
     * @return
     */
    @RequestMapping("/queryAjaxReceiveAfficheList")
    public PageInfo<OpReceiveAffiche> queryAjaxReceiveAfficheList(@RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                                                                  @RequestBody OpReceiveAffiche receiveAffiche,
                                                                  @RequestParam(value = "subjectData", required = false, defaultValue = "false") boolean subjectData,
                                                                  @RequestParam(value = "courseData", required = false, defaultValue = "false") boolean courseData,
                                                                  @RequestParam(value = "sysUserData", required = false, defaultValue = "false") boolean sysUserData) {
        Pagination affichePage = new Pagination();
        affichePage.setCurrentPage(currentPage);
        PageInfo<OpReceiveAffiche> affichePageInfo = receiveAfficheBiz.queryReceiveAfficheList(affichePage, receiveAffiche, subjectData, courseData, sysUserData);
        return affichePageInfo;
    }

    /**
     * 查询班级通知列表
     * @param currentPage 分页
     * @param receiveAffiche 查询条件
     * @param subjectData 是否设置专业科目
     * @param courseData 是否设置课程
     * @param sysUserData 是否设置创建人
     * @return
     */
    @RequestMapping("/queryAjaxReceiveAfficheLetterList")
    public PageInfo<OpReceiveAffiche> queryAjaxReceiveAfficheLetterList(@RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                                                                  @RequestBody OpReceiveAffiche receiveAffiche,
                                                                  @RequestParam(value = "subjectData", required = false, defaultValue = "false") boolean subjectData,
                                                                  @RequestParam(value = "courseData", required = false, defaultValue = "false") boolean courseData,
                                                                  @RequestParam(value = "sysUserData", required = false, defaultValue = "false") boolean sysUserData) {
        Pagination affichePage = new Pagination();
        affichePage.setCurrentPage(currentPage);
        PageInfo<OpReceiveAffiche> affichePageInfo = receiveAfficheBiz.queryReceiveAfficheList(affichePage, receiveAffiche, subjectData, courseData, sysUserData);

        List<OpReceiveAffiche> list = affichePageInfo.getList();
        List<OpReceiveAffiche> opReceiveAfficheList=new ArrayList<>();
        Map<String, List<OpReceiveAffiche>> collect = list.stream().collect(Collectors.groupingBy(e -> e.getAfficheRandom()));
        collect.forEach((k,v)->{
            String userIds = v.stream().map(f -> f.getUserId().toString()).collect(Collectors.joining(","));
            Map<String,Object> condition = new HashMap<>();
            condition.put("ids",userIds);
            List<Map<String, Object>> userList = cusUserService.queryUserList(condition, false, false, false, false, false, false, false);
            v.get(0).setUser(userList);
            v.get(0).setUserIds(userIds);
            opReceiveAfficheList.add(v.get(0));
            affichePageInfo.setList(opReceiveAfficheList);
        });

        return affichePageInfo;
    }

    /**
     * 修改接收消息状态
     *
     * @param userId 用户id
     */
    @RequestMapping("/updateReceiveArticleStatusById")
    public Map<String, Object> updateReceiveArticleStatusById(@RequestParam("userId") BigDecimal userId) {
        receiveAfficheBiz.updateReceiveArticleStatusById(userId);
        return ResultUtil.SUCCESS();
    }

    /**
     * 删除接收消息
     *
     * @param receiveAfficheId
     */
    @RequestMapping("/deleteReceiveAffiche")
    public Map<String, Object> deleteReceiveAffiche(@RequestParam("receiveAfficheId") BigDecimal receiveAfficheId) {
        receiveAfficheBiz.deleteReceiveAffiche(receiveAfficheId);
        return ResultUtil.SUCCESS("删除消息成功");
    }

    /**
     * 删除接收消息
     *saveReceiveAffiche
     * @param ids 消息Id串
     */
    @RequestMapping("/deleteReceiveAfficheIds")
    public Map<String,Object> deleteReceiveAfficheIds(@RequestParam("ids") String ids,@RequestParam("userId") BigDecimal userId){
        ids = StringUtils.subHeadTailString(ids,",");
        if(StringUtils.isNotEmpty(ids)){
            receiveAfficheBiz.deleteReceiveAfficheIds(ids,userId);
        }
        return ResultUtil.SUCCESS("删除消息成功");
    }


    /**
     * 批量系统发布消息
     * Map<String,String> 中 userId，context，msgType
     * @param json
     */
    @RequestMapping("/sendAfficheToUser")
    public Map<String,Object> sendAfficheToUser(@RequestParam("json") String json){
        receiveAfficheBiz.sendAfficheToUser(json);
        return ResultUtil.SUCCESS("发送成功");
    }

    /**
     * 保存消息
     *
     * @param receiveAfficheMap 消息
     * @return 保存结果
     */
    @RequestMapping("/saveReceiveAffiche")
    public Map<String, Object> saveReceiveAffiche(@RequestBody Map<String,Object> receiveAfficheMap) {
        Map<String, Object> check = this.checkReceiveAffiche(receiveAfficheMap);
        if (check != null) {
            return check;
        }
        if((StringUtils.isEmpty(receiveAfficheMap.get("userIds"))||receiveAfficheMap.get("userIds").equals("0") )&& ObjectUtils.isNotEmpty(receiveAfficheMap.get("classId")) ){

                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("classesId",new BigDecimal((String) receiveAfficheMap.get("classId")));
                List<Map<String, Object>> classesMemberList = classesMemberService.findClassesMemberList(objectObjectHashMap, false, 1, 1,2);
                   String   userIds = DataUtil.joining(classesMemberList, (v) -> v.get("memberId"));
                 if(StringUtils.isEmpty(userIds)){
                     return ResultUtil.ERROR("没有可以接收消息的用户");
                 }
                   receiveAfficheMap.put("userIds",userIds);
        }
        OpReceiveAffiche receiveAffiche = new OpReceiveAffiche();
        receiveAffiche.setContext((String) receiveAfficheMap.get("context"));
        receiveAffiche.setMsgType((Integer)receiveAfficheMap.get("msgType"));
        receiveAffiche.setStatus((Integer)receiveAfficheMap.get("status"));
        if(ObjectUtils.isNotEmpty(receiveAfficheMap.get("createUserId"))){
            receiveAffiche.setCreateUserId(new BigDecimal(receiveAfficheMap.get("createUserId").toString()));
        }
        String userIds = receiveAfficheMap.get("userIds").toString();
        String afficheRandom ="";
        if (ObjectUtils.isNotEmpty(receiveAfficheMap.get("classId"))) {
            receiveAffiche.setClassId(new BigDecimal((String) receiveAfficheMap.get("classId")));
            afficheRandom = StringUtils.getRandomString(32);
        }


        String[] split = userIds.split(",");
        List opReceiveAfficheList  =  new  ArrayList<OpReceiveAffiche>();
        for (String userId : split) {
            OpReceiveAffiche receiveAfficheTo = new OpReceiveAffiche();
            receiveAfficheTo.setId(null);
            receiveAfficheTo.setUserId(new BigDecimal(userId));
            receiveAfficheTo.setContext((String) receiveAfficheMap.get("context"));
            receiveAfficheTo.setMsgType((Integer) receiveAfficheMap.get("msgType"));
            receiveAfficheTo.setStatus((Integer) receiveAfficheMap.get("status"));
            if (ObjectUtils.isNotEmpty(receiveAfficheMap.get("classId"))) {
                receiveAfficheTo.setClassId(new BigDecimal((String) receiveAfficheMap.get("classId")));
            }
            if(StringUtils.isNotEmpty(afficheRandom)){
                receiveAfficheTo.setAfficheRandom(afficheRandom);
            }
            if(ObjectUtils.isNotEmpty(receiveAfficheMap.get("createUserId"))){
                receiveAfficheTo.setCreateUserId(new BigDecimal(receiveAfficheMap.get("createUserId").toString()));
            }
            opReceiveAfficheList.add(receiveAfficheTo);
            receiveAfficheBiz.setUpdateNum(receiveAfficheTo.getUserId());
        }
        receiveAfficheBiz.batchSave(opReceiveAfficheList);
        return ResultUtil.SUCCESS("发送消息成功");
    }

    /**
     * 检查消息数据
     * @param receiveAfficheMap 消息
     */
    private Map<String, Object> checkReceiveAffiche(Map<String,Object> receiveAfficheMap) {
        if (StringUtils.isEmpty(receiveAfficheMap.get("context"))) {
            return ResultUtil.ERROR("填写发送消息内容");
        }
        return null;
    }

    /**
     * 获取未读消息收消息数
     *
     * @param userId
     */
    @RequestMapping("/countReceiveAffiche")
    public Map<String, Object> countReceiveAffiche(@RequestParam("userId") BigDecimal userId) {
        BigDecimal bigDecimal = receiveAfficheBiz.queryUserMsgNum(userId);
        if(bigDecimal.compareTo(new BigDecimal(0))==1){
            return  ResultUtil.SUCCESS("获取成功",bigDecimal);
        }
        return  ResultUtil.SUCCESS("没有新消息",0);
    }

    /**
     * 删除接收消息
     *
     * @param afficheRandoms 消息Id串
     */
    @RequestMapping("/deleteReceiveClassAfficheIds")
    public Map<String,Object> deleteReceiveClassAfficheIds(@RequestParam("afficheRandoms") String afficheRandoms){
        afficheRandoms = StringUtils.subHeadTailString(afficheRandoms,",");
        if(StringUtils.isNotEmpty(afficheRandoms)){
            receiveAfficheBiz.deleteReceiveClassAfficheIds(afficheRandoms);
        }
        return ResultUtil.SUCCESS("删除消息成功");
    }

}
